package com.goushu.controller;

import com.goushu.pojo.*;
import com.goushu.service.CartService;
import com.goushu.service.CustomerService;
import com.goushu.utils.JwtUtil;
import com.goushu.utils.Md5Util;
import com.goushu.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/customer")
@Slf4j
public class CustomerController {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CartService cartService;

    /**
     * 顾客注册
     * @param customer
     * @return
     */
    @PostMapping("/register")
    public Result customerRegister(@RequestBody Customer customer) {
        Customer c = customerService.findByUserName(customer.getUsername());
        if (c == null) {
            customerService.customerRegister(customer);
            return Result.success();
        } else {
            return Result.error("用户名已被占用");
        }
    }

    /**
     * 顾客登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result customerLogin(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        Customer c = customerService.findByUserName(username);
        if(c == null) {
            return Result.error("用户名错误");
        }
        if(c.getRole() != 1) {
            return Result.error("该用户不是顾客");
        }
        if(Md5Util.getMD5String(password).equals(c.getPassword())) {
            // 登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", c.getId());
            claims.put("username", c.getUsername());
            String token = JwtUtil.genToken(claims);
            // 把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 12, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    /**
     * 获取顾客信息
     * @return
     */
    @GetMapping("/userInfo")
    public Result<Customer> userInfo() {
        // 根据用户名查询用户
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Customer customer = customerService.findByUserName(username);
        customer.setPassword("****");
        return Result.success(customer);
    }

    /**
     * 修改顾客头像
     * @param avatarUrl
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestBody @URL String avatarUrl) {
        customerService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 修改顾客密码
     * @param params
     * @param token
     * @return
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {

        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd)) {
            return Result.error("缺少必要参数");
        }
        // 原密码是否正确
        // 调用customerService 根据用户名拿到原密码，再和old_pwd比对
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Customer loginUser = customerService.findByUserName(username);
        if(!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码错误");
        }

        //调用service完成密码更新
        customerService.updatePwd(newPwd);
        // 删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }

    /**
     * 修改顾客信息
     * @param customer
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated Customer customer) {
        customerService.update(customer);
        return Result.success();
    }

    /**
     * 顾客提交订单
     * @param form
     * @return
     */
    @PutMapping("/order")
    public Result order(@RequestBody Map<String, Object> form) {
        // 拆分
        List<Map<String, Object>> books = (List<Map<String, Object>>) form.get("book");
        Map<String, String> data = (Map<String, String>)form.get("data");
        customerService.order(data, books);
        books.forEach(book -> {
            cartService.deleteCartByBId((Integer) book.get("bid"));
        });
        return Result.success();
    }

    /**
     * 获取订单列表
     * @return
     */
    @GetMapping("/listorder")
    public Result<List<OrderQuery>> listOrder() {
        List<OrderQuery> c = customerService.listOrder();
        return Result.success(c);
    }

    @PutMapping("/addComment")
    public Result addComment(@RequestBody AddComment addComment) {
        log.info("{}", addComment);
        customerService.addComment(addComment);
        customerService.modifyOrder(addComment.getOid());
        return Result.success();
    }

}
